<template>
    <div class="app-container">
        <FilterSearch v-show="showSearch" class="filter-search" :value="queryParams" :config="configData">
        </FilterSearch>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        <!-- 表格数据 -->
        <el-table v-loading="loading" :data="dataList" @selectionChange="handleSelectionChange">
            <el-table-column type="selection" minWidth="55" align="center" />
            <el-table-column type="index" label="序号" minWidth="60">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="角色名称" prop="roleName" minWidth="120" :show-overflow-tooltip="true" />
            <el-table-column prop="roleSort" label="排序" minWidth="80" sortable></el-table-column>
            <el-table-column label="权限字符" prop="roleKey" minWidth="160" :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="center" prop="status" minWidth="80">
                <template #default="scope">
                    <dict-tag :options="statusOptions" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" minWidth="200" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="创建时间" align="center" sortable prop="createTime" minWidth="180">
            </el-table-column>
            <el-table-column label="更新时间" align="center" sortable prop="updateTime" minWidth="180">
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" minWidth="140"
                class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button v-hasPermi="['permission:role:edit']" link type="primary" icon="Edit"
                        @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button v-hasPermi="['permission:role:remove']" link type="primary" icon="Delete"
                        @click="handleRemove(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
            :total="total" @pagination="getList" />

        <!-- 添加或编辑角色配置对话框 -->
        <el-dialog v-model="open" :title="title" width="800px" append-to-body>
            <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="角色名称" prop="roleName">
                            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="roleKey">
                            <template #label>
                                <span>
                                    <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
                                        placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    权限字符
                                </span>
                            </template>
                            <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="角色顺序" prop="roleSort">
                            <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="dict in statusOptions" :key="dict.value" :label="dict.value">{{
                                    dict.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="菜单权限">
                            <el-checkbox v-model="menuExpand"
                                @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                            <el-checkbox v-model="menuNodeAll"
                                @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
                            <el-checkbox v-model="form.menuCheckStrictly"
                                @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
                            <el-scrollbar style="width:100%;height:200px;">
                                <div>
                                    <el-tree ref="menuRef" class="tree-border"
                                        :props="{ label: 'menuName', children: 'children' }" :data="menuOptions"
                                        show-checkbox node-key="menuId" :check-strictly="!form.menuCheckStrictly"
                                        empty-text="加载中，请稍候"></el-tree>
                                </div>
                            </el-scrollbar>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" type="textarea" rows="3" resize="none"
                                placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup name="Role" lang="ts">
/* eslint-disable camelcase */
import {
    roleList,
    roleAdd,
    roleEdit,
    roleRemove
} from '@/api/permission/role';
import { menuList } from '@/api/system/menu';
import { getCurrentInstance, ComponentInternalInstance, ref, reactive, toRefs, nextTick, computed } from 'vue';
import { statusOptions } from "@/constant";
import { FormInstance } from 'element-plus';

interface RoleItem {
    id?: number;
    roleName?: string;
    roleKey?: string;
    status?: string;
    remark?: string;
    menuIds?: number[];
    roleSort?: number;
    [key: string]: any;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dataList = ref<any[]>([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref('');
const menuOptions = ref<any[]>([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const menuRef = ref<any>(null);

const data = reactive<{
    form: RoleItem;
    queryParams: any;
    rules: any;
}>({
    form: {} as RoleItem,  // 类型断言应该在这里
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined,
    },
    rules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
        roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }],
    },
});
const handleChecked = reactive<{
    ids: number[],
    multiple: boolean
}>({
    ids: [],
    multiple: true
})
const { queryParams, form, rules } = toRefs(data);
const { ids, multiple } = toRefs(handleChecked);
const configData = computed(() => {
    let config = {
        itemConfig: [
            {
                type: "input",
                prop: "roleName",
                label: "角色名称",
                placeholder: "请输入"
            },
            {
                type: "input",
                prop: "roleKey",
                label: "权限字符",
                placeholder: "请输入"
            },
            {
                type: "select",
                prop: "status",
                label: "状态",
                placeholder: "请选择",
                optList: statusOptions
            },
            {
                type: "datetimerange",
                prop: "createTime",
                label: "创建时间",
                dateFormate: "YYYY-MM-DD HH:mm:ss",
                placeholder: "请选择"
            }
        ],
        operate: [
            {
                icon: "Search",
                type: "primary",
                name: "查询",
                handleClick: getList,
                rule: false,
            },
            {
                icon: "RefreshRight",
                type: "info",
                name: "重置",
                handleClick: reset,
                rule: false,
            },
            {
                icon: "Plus",
                type: "success",
                name: "新增",
                handleClick: add,
                disabled: !checkPermission('permission:role:add'),
                rule: true
            },
            {
                icon: "Delete",
                type: "danger",
                name: "删除",
                handleClick: remove,
                rule: false,
                disabled: multiple.value
            }
        ],
        rules: {},
    };
    return config;
});

/** 查询角色列表 */
function getList() {
    loading.value = true;
    roleList(queryParams.value).then((response: any) => {
        dataList.value = response.data.rows;
        total.value = response.data.total;
        loading.value = false;
    });
}

function checkPermission(permission: string) {
    return proxy!.$auth.hasPermi(permission)
}
/** 删除按钮操作 */
function remove(row: any) {
    proxy!.$modal
        .confirm('是否确认删除角色编号为"' + ids.value + '"的数据项?')
        .then(function () {
            return roleRemove(ids);
        })
        .then((res: any) => {
            getList();
            proxy!.$modal.msgSuccess(res.msg);
        });
}
/** 删除按钮操作 */
function handleRemove(row: RoleItem) {
    proxy!.$modal
        .confirm('是否确认删除角色名称为"' + row.roleName + '"的数据项?')
        .then(function () {
            return roleRemove([row.id]);
        })
        .then((res: any) => {
            getList();
            proxy!.$modal.msgSuccess(res.msg);
        });
}
/** 多选框选中数据 */
function handleSelectionChange(selection: any[]) {
    ids.value = selection.map(item => item.id);
    if (ids.value.length > 0) {
        if (checkPermission('permission:role:remove')) {
            multiple.value = false
        }
    } else {
        multiple.value = true;
    }
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
    menuList().then(response => {
        menuOptions.value = proxy!.handleTree(response.data, "menuId");
    });
}
/** 重置新增的表单以及其他数据  */
function reset() {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined,
    };
    getList();
}
/** 添加角色 */
function add() {
    title.value = '新增角色';
    open.value = true;
}
/** 编辑角色 */
function handleEdit(row: RoleItem) {
    form.value = {
        id: row.id,
        roleId: row.roleId,
        roleName: row.roleName,
        roleKey: row.roleKey,
        roleSort: row.roleSort,
        status: row.status,
        menuIds: row.menuIds,
        remark: row.remark
    };
    title.value = '编辑角色';
    open.value = true;
    row.menuIds.forEach(async (v: any) => {
        await nextTick();
        menuRef.value.setChecked(v, true)
    })
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value: any, type: any) {
    let treeList = menuOptions.value as any;
    for (let i = 0; i < treeList.length; i++) {
        menuRef.value.store.nodesMap[treeList[i].menuId].expanded = value;
    }
}
/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value: any, type: string) {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value: any, type: string) {
    form.value.menuCheckStrictly = value ? true : false;
}
/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
}
/** 提交按钮 */
function submitForm() {
    (proxy?.$refs['roleRef'] as any).validate((valid: any) => {
        if (valid) {
            if (form.value.id !== undefined) {
                form.value.menuIds = getMenuAllCheckedKeys();
                roleEdit(form.value).then(response => {
                    proxy!.$modal.msgSuccess(response.msg);
                    cancel();
                    getList();
                });
            } else {
                form.value.menuIds = getMenuAllCheckedKeys();
                roleAdd(form.value).then(response => {
                    proxy!.$modal.msgSuccess(response.msg);
                    cancel();
                    getList();
                });
            }
        }
    });
}
/** 取消按钮 */
function cancel() {
    if (menuRef.value) {
        menuRef.value.setCheckedKeys([]);
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    const roleFormRef = proxy?.$refs['roleRef'] as FormInstance | undefined;
    if (roleFormRef?.resetFields) {
        roleFormRef.resetFields();
    }
    open.value = false;
}

getList();
getMenuTreeselect();
</script>
